package com.longxi.tianjintianbao.ui.presenter.main;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.main.IBrowserAtView;

public class BrowserAtPresenter extends BasePresenter<IBrowserAtView> {

    private String mDefaultUserAgent;
    private String mDesktopUserAgent;

    public BrowserAtPresenter(BaseActivity context) {
        super(context);
    }

    public void getData() {
        Intent intent = mContext.getIntent();
        String url =intent.getStringExtra("url");

        WebSettings webSettings = getView().getWebView().getSettings();
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setDomStorageEnabled(true);

        webSettings.setDatabaseEnabled(false);//数据缓存
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setJavaScriptEnabled(true);//如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript

        initializeUserAgents();
//        updateUserAgent();

        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        getView().getWebView().setWebChromeClient(new ChromeClient());
        getView().getWebView().setWebViewClient(new ViewClient());

        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。

        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        getView().getWebView().loadUrl(url);
    }

    private void initializeUserAgents() {
        mDefaultUserAgent = getView().getWebView().getSettings().getUserAgentString();
        mDesktopUserAgent = mDefaultUserAgent
                .replaceFirst("\\(Linux;.*?\\)", "(X11; Linux x86_64)")
                .replace("Mobile Safari/", "Safari/");
    }

//    private void updateUserAgent() {
//        boolean requestDesktopSite = Settings.REQUEST_DESKTOP_SITE_IN_WEBVIEW.getValue();
//        WebSettings webSettings = mWebView.getSettings();
//        String oldUserAgent = webSettings.getUserAgentString();
//        boolean changed = false;
//        if (requestDesktopSite && !TextUtils.equals(oldUserAgent, mDesktopUserAgent)) {
//            webSettings.setUserAgentString(mDesktopUserAgent);
//            changed = true;
//        } else if (!requestDesktopSite && !TextUtils.equals(oldUserAgent, mDefaultUserAgent)) {
//            // This will requrie API level 17.
//            //webSettings.setUserAgentString(WebSettings.getDefaultUserAgent(this));
//            webSettings.setUserAgentString(mDefaultUserAgent);
//            changed = true;
//        }
//        String url = mWebView.getUrl();
//        if (!TextUtils.isEmpty(url) && changed) {
//            if (requestDesktopSite) {
//                String doubanDesktopSiteUrl = getDoubanDesktopSiteUrl(url);
//                if (!TextUtils.equals(url, doubanDesktopSiteUrl)) {
//                    mWebView.loadUrl(doubanDesktopSiteUrl);
//                } else {
//                    mWebView.reload();
//                }
//            } else {
//                mWebView.reload();
//            }
//        }
//    }

    private class ChromeClient extends WebChromeClient {

        // NOTE: WebView can be trying to show an AlertDialog after the activity is finished, which
        // will result in a WindowManager$BadTokenException.
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return mContext.isFinishing() || super.onJsAlert(view, url, message,
                    result);
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            return mContext.isFinishing() || super.onJsConfirm(view, url, message,
                    result);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
                                  JsPromptResult result) {
            return mContext.isFinishing() || super.onJsPrompt(view, url, message,
                    defaultValue, result);
        }

        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            return mContext.isFinishing() || super.onJsBeforeUnload(view, url, message,
                    result);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
        }

        // For API level <= 15.
        //@Override
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType) {
        }

        // For 16 <= API level <= 19.
        //@Override
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType,
                                    String capture) {
            openFileChooser(uploadFile, acceptType);
        }

        // For API level >= 21.
        @Override
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                         FileChooserParams fileChooserParams) {
            return true;
        }
    }

    private class ViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            mContext.showLoading();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            mContext.hideLoading();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description,
                                    String failingUrl) {
            mContext.showError();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return true;
        }
    }
}
